var twitter = {};

twitter.Application = function(){};
core.extendClass('twitter.Application', 'core.JSApplication');

twitter.Application.prototype.startBounce = function(aCount){
    if(!this.counter)
        return;
    $(this.counter).html(aCount>0?aCount:'');
}

twitter.Application.prototype.stopBounce = function(){
    if(!this.counter)
        return;
    $(this.counter).html('');
}

twitter.Application.prototype.loadDockIndicator = function(aWorkspace){
    var instance = this;
    var d = core.newDiv(null, 'dock_icon tweet_icns twitter');
    $(d).html('');
    d.side = 25;
    aWorkspace.dockElement.menu = [
        {
            text: 'Close application',
            handler: function(){
                instance.sendMessage('stopApplication');
            }
        }
    ]
    aWorkspace.dockElement.addElement(d);
    this.counter = core.newDiv(null, 'dock_icon twitter_counter');
    this.counter.side = 25;
    aWorkspace.dockElement.addElement(this.counter);
//    aWorkspace.dockElement.menu = [{
//            text: 'Menu item, close for example',
//            handler: function(){
//                return true;
//            }
//    }]
};

twitter.TwitterFrame = function(){};
core.extendClass('twitter.TwitterFrame', 'core.JSFrame');

twitter.TwitterFrame.prototype.tweetsLoading = function(){
    this.table.clear();
    this.table.addRow(0, ['<div class="tweets_loading">Loading timeline...</div>', 1]);
    this.table.bodyChanged();
}

twitter.TwitterFrame.prototype.markAsRead = function(aRow, aRead){
    aRow[2] = aRead;
    if(aRead){
        $(aRow[0]).removeClass('tweet_new');
        $(aRow[4]).removeClass('tweet_icn_star').addClass('tweet_icn_star_empty');
    }else{
        $(aRow[0]).addClass('tweet_new');
        $(aRow[4]).addClass('tweet_icn_star').removeClass('tweet_icn_star_empty');
    }
};

twitter.TwitterFrame.prototype.loadContents = function(){
    var instance = this;
    var toolbar = new core.Tabs({
        toolbar: true,
        cls: 'toolbar'
    });
    this.paused = false;
    this.pauseButton = new core.form.Button({
        icon: 'tweet_icns tweet_icn_pause',
        tooltip: 'Enable/disable automatic new tweets fetching',
        handler: function(){
            instance.pauseButton.setIcon(instance.paused?'tweet_icns tweet_icn_pause':'tweet_icns tweet_icn_play');
            instance.send({
                method: 'playPause',
                disable: instance.table
            });
        }
    });
    toolbar.addTab(new core.form.Button({
        icon: 'tweet_icns tweet_icn_reload',
        tooltip: 'Fetch new tweets',
        handler: function(){
            instance.send({
                method: 'updateTwitter',
                disable: instance.table
            });
        }
    }), new core.form.Button({
        tooltip: 'Change settings',
        icon: 'tweet_icns tweet_icn_options',
        handler: function(){
            instance.sendMessage('showSettings');
        }
    }), new core.form.Button({
        tooltip: 'Mark all tweets as read',
        icon: 'tweet_icns tweet_icn_allread',
        handler: function(){
            instance.sendMessage('markAllRead', {}, function(data){
                instance.loadGrid(data);
            }, null, instance.table);

        }
    }), this.pauseButton
    );

    this.frame.addToolbar(toolbar);

    this.textArea = new core.form.TextArea({
        colspan: 2
    });
    this.textStatus = new core.Label({
        align: 'left',
        valign: 'middle',
        text: 'Characters: 0'
    });
    this.pagerBox = new core.Box({
        formless: true
    });
    this.textArea.minHeight = 60;
    this.textArea.on('change', function(t){
        instance.textStatus.setText('Characters: '+t.getValue().length);
    });
    this.textArea.on('keydown', function(t, e){
        if(e.which==13 || e.which==10){
            var textToSend = $.trim(t.getValue());
            if(textToSend.length>0){
//                core.log('Sending '+textToSend);
                instance.sendMessage('updateStatus', {
                    message: textToSend
                }, function(){
                    instance.textArea.setValue('');
                }, null, instance.textArea);
            }
            return false;
        }
        return true;
    });

    this.table = new core.grid.GridPanel({
        allowRowSelect: true,
        pager: true,
        pagerBox: this.pagerBox,
        frame: this,
        colspan: 2,
        idIndex: 1
    });
    this.table.on('add_item', function(table, aData){
        var rootDiv = core.newDiv(null, 'tweet');
        var contentDiv = core.newDiv(rootDiv, 'tweet_content');
        var star = core.newElement(contentDiv, 'img', 'icon tweet_star tweet_icns');
        star.src = 'res/core/sp.png';
        star.tweet = aData.id;
        $(star).css('float', 'right').click(function(){
            instance.markAsRead(instance.table.getRow(this.tweet), false);
            instance.sendMessage('markAsUnread', {
                id: this.tweet
            });
            return false;
        });
        if(!aData.read){
            $(rootDiv).addClass('tweet_new');
            $(star).addClass('tweet_icn_star');
        }else{
            $(star).addClass('tweet_icn_star_empty');
        }
        var img = core.newElement(contentDiv, 'img', 'tweet_avatar');
        $(img).attr('src', aData.avatar).attr('align', 'left');
        var titleSpan = core.newElement(contentDiv, 'span', 'tweet_title');
        var textSpan = core.newElement(contentDiv, 'span', 'tweet_text');
        var footer = core.newDiv(rootDiv, 'tweet_footer');
        $(titleSpan).html(aData.title+'<br/>');
        $(textSpan).html(aData.text);
        var footerSpan = core.newElement(footer, 'span', 'tweet_footer_text');
        $(footerSpan).html('['+aData.date+']');
        var reply = core.newElement(footer, 'img', 'icon tweet_icns tweet_icn tweet_icn_reply');
        reply.src = 'res/core/sp.png';
        $(reply).click(function(e){
    //        core.log('reply to message'+this.tweet);
            instance.startReply(this.tweet);
            return false;
        });
        reply.tweet = aData.id;
        $(footer).append(reply);

        var link = core.newElement(footer, 'img', 'icon tweet_icns tweet_icn tweet_icn_link');
        link.src = 'res/core/sp.png';
        $(link).click(function(e){
    //        core.log('reply to message'+this.tweet);
            window.open('http://twitter.com/'+this.user+'/status/'+this.tweet);
            return false;
        });
        link.tweet = aData.tweetID;
        link.user = aData.title;
        $(footer).append(link);
        if(aData.removable){
            var remove = core.newElement(footer, 'img', 'icon tweet_icns tweet_icn tweet_icn_remove');
            remove.src = 'res/core/sp.png';
            $(remove).click(function(e){
        //        core.log('reply to message'+this.tweet);
    //            instance.startReply(this.tweet);
                instance.sendMessage('destroyStatus', {
                    id: this.tweet
                }, null, null, instance.table);
                return false;
            });
            remove.tweet = aData.id;
            $(footer).append(remove);
        }
        return [rootDiv, aData.id, aData.read || false, aData.title, star, aData.tweetID];
    });
    this.table.on('select', function(el, event, id, row){
//        instance.application.stopBounce();
        instance.markAsRead(row, true);
        $(row[0]).addClass('tweet_selected');
        instance.sendMessage('selectionChanged', {
            id: id
        });
        return false;
    });
    this.table.on('unselect', function(el, event, id, row){
        $(row[0]).removeClass('tweet_selected');
    });
    this.table.on('dblclick', function(el, event, id, row){
        if(id && row){
            window.open('http://twitter.com/'+row[3]+'/status/'+row[5]);
        }
        return false;
    });
//#ifdef DESKTOP
    var findUnread = function(table, aNextPage){
        for (var i = table.getRowCount()-1; i >= 0 ; i--) {
            var row = table.getRowAt(i);
            if(!row[2]){
                table.selectRow(row[1]);
                return false;
            }
        }
        if(table.page>1 && aNextPage){
            table.changePage('left', function(){
                findUnread(table, false);
            })
        }
        return false;
    }
    this.table.on('keypress', function(table, e){
        if(e.which==32){
            findUnread(table, true);
            return false;
        }
        return true;
    });
//#endif
    this.setContent([this.textArea, this.textStatus, this.pagerBox, this.table], '1, d', 'd, d, 1', this.table);
//    this.tweetsLoading();
    this.sendMessage('loadGrid', {
        sendCounter: true
    }, function(data){
        instance.table.loadGrid(data);
//        instance.table.selectRow(data.selected);
    }, null, this.table);
};

twitter.SettingsDialog = function(){};
core.extendClass('twitter.SettingsDialog', 'core.JSDialog');

twitter.TwitterFrame.prototype.newTweets = function(aData){
    this.application.startBounce(aData.count);
    this.paused = aData.paused;
//    core.log('Paused: ', this.paused);
    this.pauseButton.setIcon(this.paused?'tweet_icns tweet_icn_play':'tweet_icns tweet_icn_pause');
};

twitter.TwitterFrame.prototype.startReply = function(aID){
    var row = this.table.getRow(aID);
    if(!row)
        return;
    var txt = '@'+row[3]+' ';
    this.textArea.setValue(txt);
    $(this.textArea.control).moveCursor(txt.length);
    this.sendMessage('startReply', {
        replyto: row[5],
        replytouser: row[3]
    }, null, function(){

    });
    this.textArea.doFocus();
}

twitter.TwitterFrame.prototype.gridItemAdded = function(aData){
    this.table.gridItemAdded(aData);
};
twitter.TwitterFrame.prototype.gridItemRemoved = function(aData){
    this.table.gridItemRemoved(aData);
};
twitter.TwitterFrame.prototype.gridItemSelected = function(aData){
    this.table.gridItemSelected(aData);
};
twitter.TwitterFrame.prototype.loadGrid = function(aData){
    this.table.loadGrid(aData);
};

twitter.SettingsDialog.prototype.createDialog = function(aData){
    var instance = this;
    var lbl = new core.Label({
        align: 'left',
        valign: 'middle',
        text: 'Click <a href="'+aData.url+'" target="_blank">here</a> to grant permissions to access your twitter. After finish, press <b>Verify</b> button',
        colspan: 2
    });
    var verify = new core.form.Button({
        align: 'right',
        valign: 'middle',
        text: 'Verify',
        handler: function(){
            instance.send({
                method: 'verifyClick',
                ok: function(aData){
                    verify.setText('Verified');
                    verify.setDisabled(true);
                    lbl.setText('Authorized as: '+aData.name);
                },
                disable: dlg
            });
        }
    });
    var dlg = new core.Dialog({
        title: 'Twitter settings',
        maxWidth: 400,
        columns: '0.5, 0.5, d',
        rows: 'd, d, d, d',
        items: [
            lbl, verify,
            core.createLabel('Fetch new tweets every'),
            new core.form.TextField({
                id: 'minutes'
            }),
            new core.Label({
                text: 'minutes',
                align: 'left'
            }),
            new core.form.CheckBox({
                text: 'Show notifications about new tweets',
                id: 'show_notify',
                colspan: 3
            }),
            new core.Box({
                colspan: 3,
                rows: 'd',
                columns: '1, 1',
                items:[
                    new core.form.Button({
                        text: 'Save',
                        align: 'right',
                        handler: function(){
                            instance.sendMessage('okClick', dlg.body.getValue(), null, null, dlg);
                        }
                    }),
                    new core.form.Button({
                        text: 'Cancel',
                        align: 'left',
                        handler: function(){
                            instance.sendMessage('cancelClick', dlg.body.getValue(), null, null, dlg);
                        }
                    })
                ]
            })
        ]
    });
    dlg.body.setValue(aData);
    return dlg;
};
